# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

# 福会通
APP_CONF = {
    '100348': {  # 支付宝2.4% (10---5000) D0结算
        'API_KEY': 'AD6BEF9CB2F8D627D81794238BBAA615F9EC9C0ECCD27BECB269ECF9BAF',
        'gateway': 'http://apipay.fhtcop.cn/pay',
        'query_gateway': 'http://apipay.fhtcop.cn/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s = s[:-1] + str(key)
    _LOGGER.info('fuhuitongpay sign str : %s', s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['key_sign']
    params.pop('key_sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("fuhuitongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay':
        return '1'
    return '1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('attach', str(pay.id)),
        ('pay_type', _get_pay_type(service)),
        ('userid', app_id),
        ('terminal_time', local_now().strftime('%Y%m%d%H%M%S')),
        ('req_time', local_now().strftime('%Y%m')),
        ('total_fee', str(int(pay_amount * 100))),
        ('title', 'charge'),
        ('body', 'charge'),
        ('notify_url', '{}/pay/api/{}/fuhuitongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['key_sign'] = generate_sign(parameter_dict, api_key)
    data = json.dumps(parameter_dict)
    _LOGGER.info("fuhuitongpay create: %s", data)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=data, headers=headers, timeout=5, verify=False)
    _LOGGER.info("fuhuitongpay create rsp : %s", response.text)
    if json.loads(response.text)['data']['out_trade_no']:
        order_db.fill_third_id(pay.id, json.loads(response.text)['data']['out_trade_no'])
    return {'charge_info': json.loads(response.text)['data']['url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("fuhuitongpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['attach']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('fuhuitongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['result_code'])
    trade_no = data['out_trade_no']
    total_fee = float(data['total_fee']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('fuhuitongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    api_key = _get_api_key(app_id)
    pay_id = pay_order.id
    parameter_dict = OrderedDict((
        ('userid', app_id),
        ('terminal_time', local_now().strftime('%Y%m%d%H%M%S')),
        ('req_time', local_now().strftime('%Y%m')),
        ('attach', str(pay_order.id)),
    ))
    parameter_dict['key_sign'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict)
    _LOGGER.info('fuhuitongpay query data, %s', j)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=j, headers=headers, timeout=3, verify=False)
    _LOGGER.info('fuhuitongpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['data']['result_code'])
        total_fee = float(data['data']['total_fee']) / 100.0
        trade_no = data['data']['out_trade_no']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 支付状态：“1”支付成功 ，“2”未支付，“3”支付失败，“4”支付中，“5”支付状态未知
        if trade_status == '1' and total_fee > 0.0:
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('fuhuitongpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
